package com.kaizeli.website.controller;

import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.ContractPersonnelImportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 合同人员导入控制器
 *
 * @author Kaizeli
 * @date 2024-10-21
 */
@Slf4j
@RestController
@RequestMapping("/api/contract-personnel-import")
@SecurityRequirement(name = "Bearer Authentication")
@Tag(name = "合同人员导入接口", description = "合同人员Excel导入相关接口")
public class ContractPersonnelImportController {

    @Autowired
    private ContractPersonnelImportService contractPersonnelImportService;

    @PostMapping("/import")
    @Operation(summary = "导入合同人员Excel（新增模式）", description = "上传Excel文件，批量导入合同人员数据。如果记录已存在则跳过")
    public Result<Map<String, Object>> importContractPersonnelExcel(
            @RequestParam("file") MultipartFile file) {

        log.info("接收到合同人员导入请求（新增模式），文件名：{}", file.getOriginalFilename());

        try {
            Map<String, Object> result = contractPersonnelImportService.importContractPersonnelExcel(file, false);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(500, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("导入合同人员Excel失败", e);
            return Result.error(500, "导入失败：" + e.getMessage());
        }
    }

    @PostMapping("/import-update")
    @Operation(summary = "导入合同人员Excel（更新模式）", description = "上传Excel文件，批量导入合同人员数据。如果记录已存在则更新，不存在则新增")
    public Result<Map<String, Object>> importContractPersonnelExcelWithUpdate(
            @RequestParam("file") MultipartFile file) {

        log.info("接收到合同人员导入请求（更新模式），文件名：{}", file.getOriginalFilename());

        try {
            Map<String, Object> result = contractPersonnelImportService.importContractPersonnelExcel(file, true);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(500, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("导入合同人员Excel失败", e);
            return Result.error(500, "导入失败：" + e.getMessage());
        }
    }

    @GetMapping("/template")
    @Operation(summary = "下载合同人员导入模板", description = "下载Excel模板文件，用于批量导入合同人员")
    public ResponseEntity<byte[]> downloadTemplate() {

        log.info("接收到下载合同人员模板请求");

        try {
            byte[] templateBytes = contractPersonnelImportService.downloadTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    java.net.URLEncoder.encode("合同人员导入模板.xlsx", "UTF-8"));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(templateBytes);

        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/import/help")
    @Operation(summary = "获取导入说明", description = "获取合同人员Excel导入的字段说明和注意事项")
    public Result<Map<String, Object>> getImportHelp() {

        Map<String, Object> help = new java.util.HashMap<>();
        help.put("title", "合同人员Excel导入说明");

        Map<String, String> fields = new java.util.HashMap<>();
        fields.put("合同ID", "必填，关联的合同ID");
        fields.put("姓名", "必填，人员姓名");
        fields.put("类型", "必填，人员类型");
        fields.put("角色", "必填，人员角色");
        fields.put("部门", "必填，所属部门");
        fields.put("开始日期", "必填，日期格式");
        fields.put("结束日期", "必填，日期格式");
        fields.put("价格", "必填，数字格式");
        fields.put("价格类型", "必填，如：日薪、月薪等");
        fields.put("联系人ID", "必填，联系人ID");
        help.put("fields", fields);

        java.util.List<String> notes = java.util.Arrays.asList(
                "1. Excel第一行为字段名称，第二行开始为数据",
                "2. 合同ID+姓名+角色 组合唯一，不能重复",
                "3. 所有标记为必填的字段都不能为空",
                "4. 建议先下载模板，参考示例数据填写",
                "5. 支持批量导入",
                "6. 文件格式支持.xlsx和.xls"
        );
        help.put("notes", notes);

        return Result.success(help);
    }
}

